package com.ruoyi.common.utils.file;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.apache.poi.util.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.utils.StringUtils;

import javax.imageio.ImageIO;

/**
 * 图片处理工具类
 *
 * @author ruoyi
 */
public class ImageUtils
{
    private static final Logger log = LoggerFactory.getLogger(ImageUtils.class);

    public static byte[] getImage(String imagePath)
    {
        InputStream is = getFile(imagePath);
        try
        {
            return IOUtils.toByteArray(is);
        }
        catch (Exception e)
        {
            log.error("图片加载异常 {}", e);
            return null;
        }
        finally
        {
            IOUtils.closeQuietly(is);
        }
    }

    public static InputStream getFile(String imagePath)
    {
        try
        {
            byte[] result = readFile(imagePath);
            result = Arrays.copyOf(result, result.length);
            return new ByteArrayInputStream(result);
        }
        catch (Exception e)
        {
            log.error("获取图片异常 {}", e);
        }
        return null;
    }

    /**
     * 读取文件为字节数据
     * 
     * @param url 地址
     * @return 字节数据
     */
    public static byte[] readFile(String url)
    {
        InputStream in = null;
        try
        {
            if (url.startsWith("http"))
            {
                trustAllHosts();
                // 网络地址
                URL urlObj = new URL(url);
                URLConnection urlConnection = urlObj.openConnection();
                urlConnection.setConnectTimeout(30 * 1000);
                urlConnection.setReadTimeout(60 * 1000);
                urlConnection.setDoInput(true);
                in = urlConnection.getInputStream();
            }
            else
            {
                // 本机地址
                String localPath = RuoYiConfig.getProfile();
                String downloadPath = localPath + StringUtils.substringAfter(url, Constants.RESOURCE_PREFIX);
                in = new FileInputStream(downloadPath);
            }
            return IOUtils.toByteArray(in);
        }
        catch (Exception e)
        {
            log.error("获取文件路径异常 {}", e);
            return null;
        }
        finally
        {
            IOUtils.closeQuietly(in);
        }
    }



    public static void trustAllHosts() {
        try {
            javax.net.ssl.TrustManager[] trustAllCerts = new javax.net.ssl.TrustManager[]{
                    new javax.net.ssl.X509TrustManager() {
                        public java.security.cert.X509Certificate[] getAcceptedIssuers() { return null; }
                        public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) { }
                        public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) { }
                    }
            };

            javax.net.ssl.SSLContext sc = javax.net.ssl.SSLContext.getInstance("SSL");
            sc.init(null, trustAllCerts, new java.security.SecureRandom());
            javax.net.ssl.HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
            javax.net.ssl.HttpsURLConnection.setDefaultHostnameVerifier((hostname, session) -> true);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 将多个图片（URL 或本地路径）水平拼接为一张大图，并返回其 PNG 格式的字节数组
     * @param imagePaths 图片路径数组（支持 http, https, file, classpath 等，前提是 ImageUtils.getImage 支持）
     * @return 拼接后的图片字节数组（PNG格式），失败返回 null
     */
    public static byte[] concatImagesHorizontally(String[] imagePaths) {
        if (imagePaths == null || imagePaths.length == 0) {
            return null;
        }

        List<BufferedImage> images = new ArrayList<>();
        int totalWidth = 0;
        int maxHeight = 0;

        // 第一步：加载所有图片
        for (String imagePath : imagePaths) {
            try {
                byte[] data = getImage(imagePath); // 复用你已有的 getImage 方法
                if (data != null && data.length > 0) {
                    BufferedImage img = ImageIO.read(new ByteArrayInputStream(data));
                    if (img != null) {
                        images.add(img);
                        totalWidth += img.getWidth();
                        maxHeight = Math.max(maxHeight, img.getHeight());
                    }
                }
            } catch (Exception e) {
                log.warn("加载图片失败: {}", imagePath, e);
            }
        }

        if (images.isEmpty()) {
            return null;
        }

        // 第二步：创建拼接画布
        BufferedImage resultImage = new BufferedImage(totalWidth, maxHeight, BufferedImage.TYPE_INT_ARGB);
        Graphics2D g2d = resultImage.createGraphics();
        g2d.setBackground(new Color(0, 0, 0, 0)); // 透明背景
        g2d.clearRect(0, 0, totalWidth, maxHeight); // 清空画布

        // 第三步：逐个绘制
        int x = 0;
        for (BufferedImage img : images) {
            g2d.drawImage(img, x, 0, img.getWidth(), maxHeight, null);
            x += img.getWidth();
        }

        g2d.dispose();

        // 第四步：转为字节数组（PNG 格式）
        try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
            ImageIO.write(resultImage, "png", baos);
            return baos.toByteArray();
        } catch (IOException e) {
            log.error("图片拼接后编码失败", e);
            return null;
        }
    }
}
